package com.zelin.content.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zelin.content.service.ContentService;
import com.zelin.dao.ContentDao;
import com.zelin.entity.ContentEntity;
import com.zelin.utils.PageUtils;
import com.zelin.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


// @Service("contentService")
@Service
public class ContentServiceImpl extends ServiceImpl<ContentDao, ContentEntity> implements ContentService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ContentEntity> page = this.page(
                new Query<ContentEntity>().getPage(params),
                new QueryWrapper<ContentEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 功能: 使用redis查询
     * 参数:
     * 返回值: java.util.List<com.zelin.entity.ContentEntity>
     * 时间: 2021/7/31 21:21
     */
    @Override
    public List<ContentEntity> findAll() {
        List<ContentEntity>  contents = (List<ContentEntity>) redisTemplate.opsForValue().get("contents");
        if(contents == null){
            //1. 如果为null，就从数据库中取出数据
            contents = this.list();
            System.out.println("正在从数据库中取得数据。。。");
            //2. 再放回数据库中
            redisTemplate.opsForValue().set("contents",contents);
            //redisTemplate.opsForValue().set("contents",contents,10, TimeUnit.MINUTES);

        }
        return contents;
    }

    /**
     * 功能: 添加广告
     * 参数:
     * 返回值: void
     * 时间: 2021/8/2 15:00
     */
    @Override
    public void add(ContentEntity content) {
        //1. 删除redis中的缓存
        //redisTemplate.delete("contents");
        //2. 添加到数据库中
        this.save(content);
    }

    @Override
    public void update(ContentEntity content) {
        //1. 删除redis中的缓存
        //redisTemplate.delete("contents");
        //2. 调用 修改方法
        this.updateById(content);
    }

    @Override
    public void delete(List<Long> ids) {
        //1. 删除redis中的缓存
        //redisTemplate.delete("contents");
        //2. 根据id删除广告
        this.removeByIds(ids);
    }

}